package com.example.demo.controller;

import com.auth0.jwt.interfaces.Claim;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.demo.model.User;
import com.example.demo.payload.DataRequest;
import com.example.demo.payload.DataResponse;
import com.example.demo.service.UserService;
import com.example.demo.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;


@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public DataResponse userLogin(@RequestBody DataRequest dataRequest) {
        if (dataRequest == null) {
            return CommonMethod.getReturnData(400,"参数错误");
        }
        /*
         *注意测试时的数据需要外层有个data{}
         */
        String userAccount = dataRequest.getString("userAccount");
        String password = dataRequest.getString("password");
        if(userService.Login(userAccount,password)==200){
            User user = new User();
            user.setUserAccount(userAccount);
            user.setUserPassword(password);
            //设置token
            String token = JwtUtil.createToken(user);//token中有userAccount与password
            Map<String, String> data = new HashMap<>();
            data.put("token",token);
            return CommonMethod.getReturnData(200,data,"登录成功");
        }else{
            return CommonMethod.getReturnData(400,"登录失败");
        }
    }

    //此方法用于从token中获取信息，用于前端登录需求
    @GetMapping("/info")
    public DataResponse userInfo(HttpServletRequest request){
        String token = request.getHeader("X-Token");//获取请求头中的Token
        Map<String, Claim> claimsMap = JwtUtil.verifyToken(token);//通过解析和验证，获取token中隐藏的信息
        //token未通过
        if(claimsMap == null){
            return CommonMethod.getReturnMessage(50000,"Token问题");
        }
        //token通过,将用户信息传回
        else{
            Map<String, String> data = new HashMap<>();
            String userAccount=claimsMap.get("userAccount").asString();
            data.put("userAccount",userAccount);
            User user=userService.getById(userService.GetUserId(userAccount));
            data.put("userAvatar",user.getUserAvatar());
            //此处应该查询所有的信息
            return CommonMethod.getReturnData(200,data,"登录成功！");
        }
    }

    //用于获取所有的个人信息
    @PostMapping("/getInfo")
    public DataResponse getInfo(@RequestBody DataRequest dataRequest){
        String userAccount= dataRequest.getString("userAccount");
        //查询用户信息
        User user=userService.GetInfo(userAccount);
        Map data=new HashMap();
        data.put("password",user.getUserPassword());
        data.put("email",user.getEmail());
        data.put("createTime",user.getCreateTime());
        data.put("role",user.getUserRole());
        data.put("updateTime",user.getUpdateTime());
        data.put("userAvatar",user.getUserAvatar());
        return CommonMethod.getReturnData(200,data,"OK");
    }

    @PostMapping("/logout")
    public DataResponse userLogout(){
        /*
         *此处应该有重置token的操作
         */
        return CommonMethod.getReturnData(200,null,"退出成功");
    }

    @PostMapping("/register")
    public DataResponse userRegister(@RequestBody DataRequest dataRequest){
        /*
        注意前端传回来的数据格式需要正确
        */
        String userAccount=dataRequest.getString("userAccount");
        String password=dataRequest.getString("password");
        String email=dataRequest.getString("email");
        //判断用户名是否重复
        if(userService.ExistAccount(userAccount)==0){
            return CommonMethod.getReturnData(400,"用户名重复");
        }
        //MD5加密密码
        password= Md5Util.generateSaltPassword(password);

        Date now =new Date();
        User user=new User();
        user.setUserPassword(password);
        user.setUserAccount(userAccount);
        user.setEmail(email);
        user.setCreateTime(now);
        //存入数据库，返回userId
        long userId=userService.Register(user);
        return CommonMethod.getReturnData(200,userId,"注册成功!");
    }

    @PostMapping("/update")
    public DataResponse update(@RequestBody DataRequest dataRequest){
        String userAccount=dataRequest.getString("userAccount");
        String email=dataRequest.getString("email");
        String password= dataRequest.getString("password");
        Date now=new Date();
        if(userService.Update(userAccount,email,password,now)){
            return CommonMethod.getReturnMessage(200,"更新成功");
        }
        return CommonMethod.getReturnMessage(400,"更新失败");
    }

    @PostMapping("/getUserId")
    public DataResponse getUserId(@RequestBody DataRequest dataRequest){
        String userAccount = dataRequest.getString("userAccount");
        Map data =new HashMap();
        int userId=userService.GetUserId(userAccount);
        data.put("userId",userId);
        return CommonMethod.getReturnData(200,data,"查询成功");
    }

    //头像上传
    @PostMapping("/uploadUserAvatar")
    public DataResponse uploadUserAvatar(@RequestParam("file") MultipartFile file,@RequestParam("userAccount") String userAccount){
        int userId = userService.GetUserId(userAccount);
        String uniqueFileName = userId + "_" + UUID.randomUUID() + "_" + (file.getOriginalFilename()); // 生成唯一文件名
        String avatarFilePath = "src/main/resources/static/UserAvatar";
        try{
            // 保存文件逻辑
            byte[] bytes = file.getBytes();
            avatarFilePath = avatarFilePath + "/" + uniqueFileName;
            Path path = Paths.get(avatarFilePath);
            Files.write(path, bytes);
            System.out.println(file.getOriginalFilename() + "保存成功");
            User updateUser=new User();
            updateUser.setId(userId);
            updateUser.setUserAvatar("http://localhost:8080/UserAvatar/"+uniqueFileName);
            Date now=new Date();
            updateUser.setUpdateTime(now);
            userService.updateById(updateUser);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonMethod.getReturnMessage(400,"上传失败");
        }
        return CommonMethod.getReturnMessageOK("ok");
    }

}
